package com.standard.logcat.fps

import android.view.Choreographer
import com.standard.logcat.logBus.LogBus

object GetFps {
    private var mStartFrameTIme: Long = 0
    private var mFrameCount = 0
    private const val MONITOR_INTERVAL = 160L

    fun getFps() {
        Choreographer.getInstance().postFrameCallback(object : Choreographer.FrameCallback {
            override fun doFrame(frameTimeNanos: Long) {
                if (mStartFrameTIme == 0L) {
                    mStartFrameTIme = frameTimeNanos
                }
                val interval = (frameTimeNanos - mStartFrameTIme) / 1000000.0f
                if (interval > MONITOR_INTERVAL) {
                    val fps = mFrameCount.toDouble() * 1000L / interval
                    val fpsStr = "FPS:${fps.toInt()}"

                    if (LogBus.title.value != fpsStr) {
                        LogBus.title.value = fpsStr
                    }

                    mFrameCount = 0
                    mStartFrameTIme = 0
                } else {
                    ++mFrameCount
                }
                Choreographer.getInstance().postFrameCallback(this)
            }
        })
    }
}